package com.example.webdome.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static String Key = "QWERYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
    public static String USER_NAME_KEY = "username";
    //生成jwt加密
    public static String createToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(USER_NAME_KEY, username);
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, Key)
                .setClaims(claims)
                .setIssuedAt(new Date())//开始时间
                .setExpiration(new Date(System.currentTimeMillis() + 24L * 60 * 60 * 60 * 1000))//销毁时间
                .compact();
        return token;
    }

    public static Claims parseJWT(String token) {
        // 解析令牌
        return Jwts.parser()
                .setSigningKey(Key) // 令牌的 盐
                .parseClaimsJws(token) // token 值
                .getBody();
    }

    public static String getEmail(Claims claims) {
        if (claims != null) {
            return (String) claims.get(USER_NAME_KEY);
        }
        return null;
    }
}
